<?php

class controller extends controllerBase {

	public function add()
	{
		global $headers;
		
		$errors = array();
		$event = new event();
		
		if(isset($_POST['submit']))
		{
			if($_POST['title'] != '')
			{
				$event->title = $_POST['title'];
			}
			else
			{
				$errors[] = 'no-title';
			}
			
			if($_POST['location'] != '')
			{
				$event->location = $_POST['location'];
			}
			else
			{
				$errors[] = 'no-location';
			}
			
			$event->description = $_POST['description'];
			
			if($_POST['date'] != '')
			{
				$date = split('/', $_POST['date']);
			}
			else
			{
				$errors[] = 'no-date';
			}
			
			if($_POST['hours'] != '' && $_POST['minutes'] != '')
			{
				if($_POST['ampm'] == 'pm')
				{
					$hours = $_POST['hours'] + 12;
				}
			}
			else
			{
				$errors[] = 'no-time';
			}
			
			$event->date = mktime($hours, $_POST['minutes'], 0, $date[0], $date[1], $date[2]);
			
			if(count($errors) == 0)
			{
				$event->save();
				$submitted = true;
			}
			
		}
		
		if($submitted)
		{
			$content = 'event added';
		}
		else
		{
			$content = form::getForm('event_add', array($errors));
		}
		
		
		include(ROOT . 'admin/skin/wrapper.php');
	}
	
	public function edit($id = 0)
	{
		global $headers;
		
		if($id == 0)
		{
			$query = new Query("SELECT * FROM `events` ORDER BY `date` DESC");
			
			if($query->num_rows() > 0)
			{
				$content .= '<table>';
				
				$events = event::RecordSet($query, 'event');
				
				foreach($events as $event)
				{
					$content .= '<tr>
									<td>' . $event->title . '</td><td><a href="edit/' . $event->id . '">Edit</a> || <a href="delete/' . $event->id . '">Delete</a></td>
								 </tr>';
				}
				$content .= '</table>';
			}
		}
		else
		{
			$errors = array();
			$event = new event($id);
			
			if(isset($_POST['submit']))
			{
				$event->title = $_POST['title'];
				$event->description = $_POST['description'];
				$event->location = $_POST['location'];

				$date = split('/', $_POST['date']);

			

				if($_POST['ampm'] == 'pm')
				{
					$hours = $_POST['hours'] + 12;
				}

				
				$event->date = mktime($hours, $_POST['minutes'], 0, $date[0], $date[1], $date[2]);
					
				$event->save();
				
				$updated = true;
			}
			
			if($updated)
			{
				$content = 'event edited';
			}
			else
			{
				$content = form::getForm('event_edit', array($errors, $event));
			}
		}
		include(ROOT . 'admin/skin/wrapper.php');
	}
	
	public function delete($id = 0)
	{
		if($id == 0)
		{
			$content = 'the item does not exist';
		}
		else
		{
			$event = new event($id);
			$event->delete();
			$content = "event deleted";
		}
		
		include(ROOT . 'admin/skin/wrapper.php');
	}

}
?>